import api from '../utils/api'

// 商品服务
export const productService = {
  // 获取商品列表（分页）
  getProducts: async (page = 1, size = 10) => {
    try {
      console.log('productService: 获取商品列表，页码:', page, '大小:', size)
      const response = await api.get('/api/products', {
        params: { page, size }
      })
      console.log('productService: 商品列表响应:', response)
      return response
    } catch (error) {
      console.error('productService: 获取商品列表失败:', error)
      throw error
    }
  },
  
  // 获取商品详情
  getProductDetail: async (productId) => {
    try {
      console.log('productService: 获取商品详情，ID:', productId)
      const response = await api.get(`/api/products/${productId}`)
      console.log('productService: 商品详情响应:', response)
      return response
    } catch (error) {
      console.error('productService: 获取商品详情失败:', error)
      throw error
    }
  },
  
  // 获取热门商品
  getHotProducts: async (limit = 8) => {
    try {
      return await api.get('/api/products/hot', {
        params: { limit }
      })
    } catch (error) {
      throw error
    }
  },
  
  // 获取分类列表
  getCategories: async () => {
    try {
      return await api.get('/api/categories')
    } catch (error) {
      throw error
    }
  },

  // 搜索商品
  searchProducts: async (keyword, page = 1, size = 10) => {
    try {
      console.log('productService: 搜索商品，关键词:', keyword, '页码:', page, '大小:', size)
      const response = await api.get('/api/products/search', {
        params: { keyword, page, size }
      })
      console.log('productService: 搜索商品响应:', response)
      return response
    } catch (error) {
      console.error('productService: 搜索商品失败:', error)
      throw error
    }
  },

  // 按分类获取商品
  getProductsByCategory: async (categoryId, page = 1, size = 10) => {
    try {
      console.log('productService: 按分类获取商品，分类ID:', categoryId, '页码:', page, '大小:', size)
      const response = await api.get(`/api/products/category/${categoryId}`, {
        params: { page, size }
      })
      console.log('productService: 按分类获取商品响应:', response)
      return response
    } catch (error) {
      console.error('productService: 按分类获取商品失败:', error)
      throw error
    }
  }
}